package com.lykj.llw.box.ui.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
import android.webkit.WebView
import android.webkit.WebViewClient
import com.alipay.sdk.app.PayTask
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ThreadUtils
import com.bytedance.applog.game.GameReportHelper
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.kwai.monitor.log.TurboAgent
import com.lykj.lib_base.app.BaseApplication
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.base.BaseFragment
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.data.bean.response.Pay2Response
import com.lykj.llw.box.data.entity.PayResult
import com.lykj.llw.box.databinding.FrgVipBinding
import com.lykj.llw.box.ui.activity.MyCouponActivity
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import okhttp3.internal.addHeaderLenient
import org.json.JSONObject

/**
 * ================================================
 * Frag-会员
 * ================================================
 *
 * @author gosha
 * @date 2023/10/12-18:14
 */
class VipFragment : BaseFragment() {
    lateinit var binding: FrgVipBinding

    private var mUrl = ""
    private var isInit = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FrgVipBinding.inflate(layoutInflater)
        initUI()
        initData()
        setListener()
        return binding.root
    }

    override fun onResume() {
        super.onResume()
        ImmersionBar.with(this).transparentBar()
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()

        if (!isInit) {
            mUrl =
                "http://hezi-h5.66wsy.com/sdkVip?token=${BaseApplication.instance?.getUserInfo()?.token}"
//        mUrl = "https://mclient.alipay.com/h5pay/h5RouteAppSenior/index.html?server_param=emlkPTI5O25kcHQ9NjAzYjtjYz15&contextId=RZ429U7hib1LX5aaVzTklik3DIaZ0hmobileclientgw29RZ42&pageToken=&refreshNoAuth=Y"
            //加载url
            binding.wvContent.loadUrl(mUrl)
            isInit = true
        }
    }

    override fun initUI() {
    }

    override fun initData() {
        initWebView()

        FlowBus.with<String>(BConstants.BUS_KEY.LOGIN_SUCCESS).register(this) {
            mUrl =
                "http://hezi-h5.66wsy.com/sdkVip?token=${BaseApplication.instance?.getUserInfo()?.token}"
            binding.wvContent.loadUrl(mUrl)
        }
    }

    private fun initWebView() {
        initWebViewSetting()
    }

    //初始化WebView设置
    private fun initWebViewSetting() {
        //启用js脚本
        binding.wvContent.settings.javaScriptEnabled = true
        //自适应图片
        binding.wvContent.settings.useWideViewPort = true
        //缩放到屏幕大小
        binding.wvContent.settings.loadWithOverviewMode = true
        binding.wvContent.settings.setSupportZoom(true)
        binding.wvContent.settings.builtInZoomControls = true
        binding.wvContent.settings.domStorageEnabled = true
        //显示原生缩放
        binding.wvContent.settings.displayZoomControls = false

        //其他细节操作
        binding.wvContent.settings.cacheMode = WebSettings.LOAD_DEFAULT
        //设置可以访问文件
        binding.wvContent.settings.allowFileAccess = true
        //支持通过JS打开新窗口
        binding.wvContent.settings.javaScriptCanOpenWindowsAutomatically = true
        //支持自动加载图片
        binding.wvContent.settings.loadsImagesAutomatically = true
        binding.wvContent.settings.defaultTextEncodingName = "utf-8"
        binding.wvContent.settings.mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW
        binding.wvContent.addJavascriptInterface(
            JsInterface(requireActivity() as BaseActivity, binding.wvContent),
            "AndroidWebView"
        )
        binding.wvContent.webViewClient = mWebView
    }

    private var mWebView = object : WebViewClient() {
        override fun shouldInterceptRequest(
            view: WebView?,
            request: WebResourceRequest?
        ): WebResourceResponse? {


            return super.shouldInterceptRequest(view, request)
        }

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }
    }

    override fun setListener() {
        binding.srlVip.setOnRefreshListener {
            if (!binding.wvContent.canGoBack()) {
                mUrl =
                    "http://hezi-h5.66wsy.com/sdkVip?token=${BaseApplication.instance?.getUserInfo()?.token}"
                binding.wvContent.loadUrl(mUrl)
            }
            it.finishRefresh(350)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }


    //JS交互接口
    class JsInterface(activity: BaseActivity, webview: WebView) {
        var mActivity: BaseActivity? = null
        var mWebView: WebView? = null

        init {
            mActivity = activity
            mWebView = webview
        }

        @JavascriptInterface
        fun switchHomeNav(index: Int) {
            FlowBus.with<String>(BConstants.BUS_KEY.HOME_SWITCH_NAV).register(mActivity!!) {
            }
        }

        @JavascriptInterface
        fun jumpToContract() {
//            ActivityUtils.startActivity(Intent(mCtx, ContractActivity::class.java))
        }

        @JavascriptInterface
        fun card() {
//            mActivity?.startActivity(Intent(mActivity, CardPackageActivity::class.java))
        }

        @JavascriptInterface
        fun FLExchange() {
//            mActivity?.startActivity(Intent(mActivity, WelfareCodeActivity::class.java))
        }

        @JavascriptInterface
        fun jumpPay(id: Int) {
            val map = HashMap<String, Any>()
            map["type"] = 2
            map["token"] = BaseApplication.instance?.getUserInfo()?.token ?: ""
            map["payInfoId"] = id
            RetrofitManager.instance.pay2(map,
                object : CustomResponseBodyObserver<ResponseBody>() {

                    override fun specificHandle(responseBody: String) {
                        try {
                            val bean = GsonUtils.fromJson(responseBody, Pay2Response::class.java)
                            alipay(bean.data.pay)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }

                    override fun handleException(ret: String, msg: String?) {
                        mActivity?.let {
                            msg?.let { it -> ToastUtils.showShort(mActivity!!, it) }
                        }
                    }
                })
        }

        private fun alipay(info: String) {
            Thread {
                val alipay = PayTask(mActivity)
                val result = alipay.payV2(info, true)
                val payResult = PayResult(result)
                val resultInfo: String? = payResult.result // 同步返回需要验证的信息
                val resultStatus: String? = payResult.resultStatus
                LogUtils.e("asd", "alipay: $resultInfo::$resultStatus::$payResult")
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    ThreadUtils.runOnUiThread {
                        ToastUtils.showShort(mActivity!!, "支付成功")

                        var jsonObj = JSONObject(resultInfo)
                        var money = jsonObj.getJSONObject("alipay_trade_app_pay_response").getDouble("total_amount").toInt()
                        LogUtils.e("$money")

                        GameReportHelper.onEventPurchase(
                            "",
                            "",
                            "",
                            1,
                            "支付宝",
                            "¥",
                            true,
                            money
                        )
                        LogUtils.e("---------巨量用户支付---已上报---------")

                        TurboAgent.onPay(money.toDouble())
                        LogUtils.e("---------快手用户支付---已上报---------")

                        val mUrl =
                            "http://hezi-h5.66wsy.com/sdkVip?token=${BaseApplication.instance?.getUserInfo()?.token}"
                        mWebView?.loadUrl(mUrl)
                    }
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    ThreadUtils.runOnUiThread {
                        ToastUtils.showShort(mActivity!!, "支付失败")
                    }
                }
            }.start()
        }

        @JavascriptInterface
        fun toCoupon() {
            ActivityUtils.startActivity(MyCouponActivity::class.java)
        }
    }
}